<?php
namespace phiction;

class database
{
    private $host = null;
    private $name = "postgres";
    private $login = "postgres";
    private $password = "";

    # option populator
    function host(string $host): self
    {
        $this->host = $host;
        return $this;
    }

    function name(string $name): self
    {
        $this->name = $name;
        return $this;
    }

    function login(string $login): self
    {
        $this->login = $login;
        return $this;
    }

    function password(string $password): self
    {
        $this->password = $password;
        return $this;
    }


    # database access
    function connect(): \PDO
    {
        return new \PDO(
            $this->source(),
            $this->login,
            $this->password,
            [
                \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
            ]);
    }

    private function source(): string
    {
        $parts = [];
        if (!is_null($this->host)) $parts[] = "host=$this->host";
        if (!is_null($this->name)) $parts[] = "dbname=$this->name";
        return 'pgsql:' . implode(';', $parts);
    }
}

